package com.pig4cloud.pigx.common.customize.api.filter.multi;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义过滤器，为了实现从请求体中多次读取数据
 *
 * @since 2022/11/12 20:28
 */
@Component
public class MultiReadBodyRequestFilter implements Filter {
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
						 FilterChain chain) throws IOException, ServletException {

		if (!(request instanceof HttpServletRequest)) {
			chain.doFilter(request, response);
		}

		// 如果是ws请求，不进行处理
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		System.err.println(servletRequest.getHeaders("x-api-ws"));
		if (Objects.equals("/ws/info", servletRequest.getRequestURI())) {
			chain.doFilter(request, response);
		}

		// 获取请求中的流如何，将取出来的字符串，再次转换成流，然后把它放入到新request对象中。
		ServletRequest requestWrapper = new MultiReadBodyRequestWrapper(servletRequest);
		chain.doFilter(requestWrapper, response);
	}
}
